package com.example.case1;

import org.apache.zookeeper.*;

import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * ClassName: DistributeServer
 * Package: com.example.case1
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-07-30
 * Time: 10:13
 */

//服务器动态上下限 服务端
public class DistributeServer {

    //连接的集群主机
    private String connectString = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
    //延迟时间
    private int sessionTimeout = 2000;
    private ZooKeeper zk;

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        //1.创建连接
        DistributeServer server = new DistributeServer();
        //连接集群
        server.getConnect();
        //2.注册服务器到集群
        //就是创建对应的路径 节点
        server.regist(args[0]);
        //3.启动业务逻辑 (睡觉)
        server.business();
    }


    private void business() throws InterruptedException {
        Thread.sleep(Long.MAX_VALUE);
    }
    private void regist(String hostname) throws InterruptedException, KeeperException {
        String create =
                zk.create("/servers/" + hostname,
                        //内容是主机名称
                        hostname.getBytes(),
                        ZooDefs.Ids.OPEN_ACL_UNSAFE,
                        //创建的临时的带序号的节点
                        CreateMode.EPHEMERAL_SEQUENTIAL);

        System.out.println(hostname + " 已经上线");
    }

    private void getConnect() throws IOException {
        zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {

            }
        });
    }

}
